using DocumentCreationSystem.Models;
using DocumentCreationSystem.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using System.IO;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// 智能自主规划系统对话框
    /// </summary>
    public partial class AutonomousPlanningDialog : Window, INotifyPropertyChanged
    {
        private readonly ILogger<AutonomousPlanningDialog> _logger;
        private readonly AutonomousPlanningService _planningService;
        private readonly AdaptiveExecutionController _executionController;
        private readonly IServiceProvider _serviceProvider;

        private DispatcherTimer _statusTimer;
        private DispatcherTimer _timeElapsedTimer;
        private DateTime _executionStartTime;
        private bool _isExecuting = false;
        private bool _isPaused = false;

        private AutonomousPlanResult? _currentResult;

        // 当前项目属性
        public Models.Project? CurrentProject { get; set; }

        public event PropertyChangedEventHandler? PropertyChanged;

        public AutonomousPlanningDialog(IServiceProvider serviceProvider)
        {
            InitializeComponent();

            _serviceProvider = serviceProvider;
            _logger = serviceProvider.GetRequiredService<ILogger<AutonomousPlanningDialog>>();
            _planningService = serviceProvider.GetRequiredService<AutonomousPlanningService>();
            _executionController = serviceProvider.GetRequiredService<AdaptiveExecutionController>();

            InitializeTimers();
            InitializeUI();

            DataContext = this;
        }

        /// <summary>
        /// 初始化定时器
        /// </summary>
        private void InitializeTimers()
        {
            // 状态更新定时器
            _statusTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(1)
            };
            _statusTimer.Tick += StatusTimer_Tick;

            // 时间计时器
            _timeElapsedTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(1)
            };
            _timeElapsedTimer.Tick += TimeElapsedTimer_Tick;
        }

        /// <summary>
        /// 初始化UI
        /// </summary>
        private void InitializeUI()
        {
            UpdateStatusIndicator("就绪", Colors.Gray);
            UpdateSystemTime();

            // 启动系统时间更新
            var systemTimeTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromSeconds(1)
            };
            systemTimeTimer.Tick += (s, e) => UpdateSystemTime();
            systemTimeTimer.Start();
        }

        /// <summary>
        /// 开始规划按钮点击
        /// </summary>
        private async void StartPlanningButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(UserRequestTextBox.Text))
                {
                    MessageBox.Show("请输入您的需求描述", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return;
                }

                await StartPlanningAsync();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "开始规划失败");
                MessageBox.Show($"开始规划失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 停止规划按钮点击
        /// </summary>
        private void StopPlanningButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StopPlanning();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "停止规划失败");
                MessageBox.Show($"停止规划失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 暂停/恢复按钮点击
        /// </summary>
        private void PauseResumeButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_isPaused)
                {
                    ResumeExecution();
                }
                else
                {
                    PauseExecution();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "暂停/恢复执行失败");
                MessageBox.Show($"操作失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 重新开始按钮点击
        /// </summary>
        private async void RestartButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var result = MessageBox.Show("确定要重新开始规划吗？当前进度将丢失。",
                    "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {
                    StopPlanning();
                    await Task.Delay(1000); // 等待停止完成
                    await StartPlanningAsync();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "重新开始失败");
                MessageBox.Show($"重新开始失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 导出结果按钮点击
        /// </summary>
        private void ExportResultsButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_currentResult == null)
                {
                    MessageBox.Show("没有可导出的结果", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
                    return;
                }

                ExportResults();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出结果失败");
                MessageBox.Show($"导出结果失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 最小化按钮点击
        /// </summary>
        private void MinimizeButton_Click(object sender, RoutedEventArgs e)
        {
            WindowState = WindowState.Minimized;
        }

        /// <summary>
        /// 关闭按钮点击
        /// </summary>
        private void CloseButton_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }

        /// <summary>
        /// 开始规划
        /// </summary>
        private async Task StartPlanningAsync()
        {
            _isExecuting = true;
            _isPaused = false;
            _executionStartTime = DateTime.Now;

            // 更新UI状态
            UpdateStatusIndicator("规划中", Colors.Orange);
            StartPlanningButton.IsEnabled = false;
            StopPlanningButton.IsEnabled = true;
            PauseResumeButton.IsEnabled = true;

            // 启动定时器
            _statusTimer.Start();
            _timeElapsedTimer.Start();

            // 清空之前的结果
            ClearPreviousResults();

            try
            {
                AddLog("开始智能自主规划...");

                // 获取用户输入
                var userRequest = UserRequestTextBox.Text;
                var projectId = GetCurrentProjectId();

                AddLog($"用户需求：{userRequest}");
                AddLog($"规划范围：{PlanningScopeComboBox.Text}");

                // 创建进度回调
                var progress = new Progress<(int progress, string message)>(update =>
                {
                    Dispatcher.Invoke(() =>
                    {
                        ExecutionProgressBar.Value = update.progress;
                        ProgressText.Text = $"进度：{update.progress}%";
                        AddLog(update.message);
                    });
                });

                // 开始规划和执行
                _currentResult = await _planningService.PlanAndExecuteAsync(userRequest, projectId, progress, GetPreferredSaveRootPath());

                // 更新UI显示结果
                await UpdatePlanningResultsAsync(_currentResult);

                UpdateStatusIndicator("完成", Colors.Green);
                AddLog("智能自主规划完成！");
            }
            catch (Exception ex)
            {
                UpdateStatusIndicator("失败", Colors.Red);
                AddLog($"规划失败：{ex.Message}");
                throw;
            }
            finally
            {
                _isExecuting = false;
                StartPlanningButton.IsEnabled = true;
                StopPlanningButton.IsEnabled = false;
                PauseResumeButton.IsEnabled = false;

                _statusTimer.Stop();
                _timeElapsedTimer.Stop();
            }
        }

        /// <summary>
        /// 停止规划
        /// </summary>
        private void StopPlanning()
        {
            if (!_isExecuting) return;

            _isExecuting = false;
            _isPaused = false;

            UpdateStatusIndicator("已停止", Colors.Gray);
            AddLog("用户停止了规划执行");

            // 更新UI状态
            StartPlanningButton.IsEnabled = true;
            StopPlanningButton.IsEnabled = false;
            PauseResumeButton.IsEnabled = false;

            _statusTimer.Stop();
            _timeElapsedTimer.Stop();
        }

        /// <summary>
        /// 暂停执行
        /// </summary>
        private void PauseExecution()
        {
            _isPaused = true;
            UpdateStatusIndicator("已暂停", Colors.Yellow);
            PauseResumeButton.Content = "▶ 恢复执行";
            AddLog("执行已暂停");
        }

        /// <summary>
        /// 恢复执行
        /// </summary>
        private void ResumeExecution()
        {
            _isPaused = false;
            UpdateStatusIndicator("执行中", Colors.Orange);
            PauseResumeButton.Content = "⏸ 暂停执行";
            AddLog("执行已恢复");
        }

        /// <summary>
        /// 更新规划结果显示
        /// </summary>
        private async Task UpdatePlanningResultsAsync(AutonomousPlanResult result)
        {
            // 更新概览
            UpdatePlanOverview(result);

            // 更新角色规划
            if (result.ExecutionResult.CharacterExecutionResult != null)
            {
                UpdateCharacterPlan(result.ExecutionResult.CharacterExecutionResult);
            }

            // 更新工作流规划
            if (result.ExecutionResult.WorkflowExecutionResult != null)
            {
                UpdateWorkflowPlan(result.ExecutionResult.WorkflowExecutionResult);
            }

            // 更新执行监控
            UpdateExecutionMonitor(result);

            // 更新统计信息
            UpdateStatistics(result);
        }

        /// <summary>
        /// 更新规划概览
        /// </summary>
        private void UpdatePlanOverview(AutonomousPlanResult result)
        {
            PlanOverviewPanel.Children.Clear();

            var overviewText = new TextBlock
            {
                Text = $@"📊 规划概览

✅ 执行状态：{(result.Success ? "成功" : "失败")}
⏱️ 执行时间：{result.ExecutionResult.CompletedAt - result.ExecutionResult.StartedAt:hh\:mm\:ss}
🎯 优化建议：{result.OptimizationSuggestions.Count} 条

📋 执行摘要：
{result.Summary}",
                FontSize = 14,
                TextWrapping = TextWrapping.Wrap,
                Margin = new Thickness(10)
            };

            PlanOverviewPanel.Children.Add(overviewText);

            // 添加规划文件路径信息
            if (!string.IsNullOrEmpty(result.PlanningFilesPath))
            {
                AddPlanningFilesSection(result);
            }
        }

        /// <summary>
        /// 添加规划文件路径显示区域
        /// </summary>
        private void AddPlanningFilesSection(AutonomousPlanResult result)
        {
            // 添加分隔线
            var separator = new Separator
            {
                Margin = new Thickness(10, 20, 10, 10)
            };
            PlanOverviewPanel.Children.Add(separator);

            // 添加标题
            var titleText = new TextBlock
            {
                Text = "📁 规划文件",
                FontSize = 16,
                FontWeight = FontWeights.Bold,
                Foreground = new SolidColorBrush(Color.FromRgb(44, 62, 80)),
                Margin = new Thickness(10, 0, 10, 10)
            };
            PlanOverviewPanel.Children.Add(titleText);

            // 添加文件夹路径（可点击）
            var folderPathPanel = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                Margin = new Thickness(10, 0, 10, 10)
            };

            var folderIcon = new TextBlock
            {
                Text = "📂 ",
                FontSize = 14,
                VerticalAlignment = VerticalAlignment.Center
            };

            var folderPathLink = new TextBlock
            {
                Text = result.PlanningFilesPath,
                FontSize = 14,
                Foreground = new SolidColorBrush(Color.FromRgb(74, 144, 226)),
                TextDecorations = TextDecorations.Underline,
                Cursor = Cursors.Hand,
                VerticalAlignment = VerticalAlignment.Center,
                Tag = result.PlanningFilesPath // 存储路径用于点击事件
            };

            // 添加点击事件
            folderPathLink.MouseLeftButtonUp += FolderPathLink_MouseLeftButtonUp;

            folderPathPanel.Children.Add(folderIcon);
            folderPathPanel.Children.Add(folderPathLink);
            PlanOverviewPanel.Children.Add(folderPathPanel);

            // 添加文件列表
            if (result.SavedFiles.Any())
            {
                var filesListText = new TextBlock
                {
                    Text = "📄 保存的文件：",
                    FontSize = 14,
                    FontWeight = FontWeights.SemiBold,
                    Margin = new Thickness(10, 10, 10, 5)
                };
                PlanOverviewPanel.Children.Add(filesListText);

                foreach (var file in result.SavedFiles)
                {
                    var filePanel = new StackPanel
                    {
                        Orientation = Orientation.Horizontal,
                        Margin = new Thickness(20, 2, 10, 2)
                    };

                    var fileIcon = new TextBlock
                    {
                        Text = GetFileIcon(file.FileType),
                        FontSize = 12,
                        VerticalAlignment = VerticalAlignment.Center,
                        Margin = new Thickness(0, 0, 5, 0)
                    };

                    var fileLink = new TextBlock
                    {
                        Text = file.FileName,
                        FontSize = 12,
                        Foreground = new SolidColorBrush(Color.FromRgb(74, 144, 226)),
                        TextDecorations = TextDecorations.Underline,
                        Cursor = Cursors.Hand,
                        VerticalAlignment = VerticalAlignment.Center,
                        Tag = file.FilePath // 存储文件路径
                    };

                    var fileInfo = new TextBlock
                    {
                        Text = $" ({file.FileType}, {FormatFileSize(file.FileSize)})",
                        FontSize = 11,
                        Foreground = new SolidColorBrush(Color.FromRgb(127, 140, 141)),
                        VerticalAlignment = VerticalAlignment.Center
                    };

                    // 添加文件点击事件
                    fileLink.MouseLeftButtonUp += FileLink_MouseLeftButtonUp;

                    filePanel.Children.Add(fileIcon);
                    filePanel.Children.Add(fileLink);
                    filePanel.Children.Add(fileInfo);
                    PlanOverviewPanel.Children.Add(filePanel);
                }
            }
        }

        /// <summary>
        /// 获取文件类型对应的图标
        /// </summary>
        private string GetFileIcon(string fileType)
        {
            return fileType switch
            {
                "规划概览" => "📊",
                "角色规划" => "👥",
                "工作流规划" => "⚙️",
                "优化建议" => "💡",
                _ => "📄"
            };
        }

        /// <summary>
        /// 格式化文件大小
        /// </summary>
        private string FormatFileSize(long bytes)
        {
            if (bytes < 1024)
                return $"{bytes} B";
            else if (bytes < 1024 * 1024)
                return $"{bytes / 1024.0:F1} KB";
            else
                return $"{bytes / (1024.0 * 1024.0):F1} MB";
        }

        /// <summary>
        /// 文件夹路径点击事件
        /// </summary>
        private void FolderPathLink_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (sender is TextBlock textBlock && textBlock.Tag is string folderPath)
                {
                    if (Directory.Exists(folderPath))
                    {
                        // 在资源管理器中打开文件夹
                        System.Diagnostics.Process.Start("explorer.exe", folderPath);
                        AddLog($"已在资源管理器中打开文件夹: {folderPath}");
                    }
                    else
                    {
                        MessageBox.Show("文件夹不存在或已被删除", "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                AddLog($"打开文件夹失败: {ex.Message}");
                MessageBox.Show($"打开文件夹失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 文件链接点击事件
        /// </summary>
        private void FileLink_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (sender is TextBlock textBlock && textBlock.Tag is string filePath)
                {
                    if (File.Exists(filePath))
                    {
                        // 在资源管理器中选中文件
                        System.Diagnostics.Process.Start("explorer.exe", $"/select,\"{filePath}\"");
                        AddLog($"已在资源管理器中定位文件: {Path.GetFileName(filePath)}");
                    }
                    else
                    {
                        MessageBox.Show("文件不存在或已被删除", "错误", MessageBoxButton.OK, MessageBoxImage.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                AddLog($"打开文件失败: {ex.Message}");
                MessageBox.Show($"打开文件失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        /// <summary>
        /// 更新角色规划显示
        /// </summary>
        private void UpdateCharacterPlan(CharacterExecutionResult characterResult)
        {
            CharacterPlanPanel.Children.Clear();

            var titleText = new TextBlock
            {
                Text = $"👥 创建了 {characterResult.CreatedCharacters.Count} 个角色",
                FontSize = 16,
                FontWeight = FontWeights.Bold,
                Margin = new Thickness(0, 0, 0, 10)
            };
            CharacterPlanPanel.Children.Add(titleText);

            foreach (var character in characterResult.CreatedCharacters)
            {
                var characterCard = CreateCharacterCard(character);
                CharacterPlanPanel.Children.Add(characterCard);
            }
        }

        /// <summary>
        /// 创建角色卡片
        /// </summary>
        private Border CreateCharacterCard(Character character)
        {
            var card = new Border
            {
                Background = new SolidColorBrush(Color.FromRgb(236, 240, 241)),
                CornerRadius = new CornerRadius(5),
                Padding = new Thickness(10),
                Margin = new Thickness(0, 5, 0, 5)
            };

            var content = new StackPanel();

            content.Children.Add(new TextBlock
            {
                Text = character.Name,
                FontSize = 14,
                FontWeight = FontWeights.Bold
            });

            if (!string.IsNullOrEmpty(character.Description))
            {
                content.Children.Add(new TextBlock
                {
                    Text = character.Description,
                    FontSize = 12,
                    Foreground = new SolidColorBrush(Colors.Gray),
                    TextWrapping = TextWrapping.Wrap,
                    Margin = new Thickness(0, 5, 0, 0)
                });
            }

            card.Child = content;
            return card;
        }

        /// <summary>
        /// 更新工作流规划显示
        /// </summary>
        private void UpdateWorkflowPlan(WorkflowExecutionResult workflowResult)
        {
            WorkflowPlanPanel.Children.Clear();

            var titleText = new TextBlock
            {
                Text = $"⚙️ 执行了 {workflowResult.StepResults.Count} 个步骤",
                FontSize = 16,
                FontWeight = FontWeights.Bold,
                Margin = new Thickness(0, 0, 0, 10)
            };
            WorkflowPlanPanel.Children.Add(titleText);

            foreach (var stepResult in workflowResult.StepResults)
            {
                var stepCard = CreateStepCard(stepResult);
                WorkflowPlanPanel.Children.Add(stepCard);
            }
        }

        /// <summary>
        /// 创建步骤卡片
        /// </summary>
        private Border CreateStepCard(StepExecutionResult stepResult)
        {
            var card = new Border
            {
                Background = new SolidColorBrush(Color.FromRgb(236, 240, 241)),
                CornerRadius = new CornerRadius(5),
                Padding = new Thickness(10),
                Margin = new Thickness(0, 5, 0, 5)
            };

            var content = new StackPanel();

            var statusIcon = stepResult.Status switch
            {
                ExecutionStatus.Completed => "✅",
                ExecutionStatus.Failed => "❌",
                ExecutionStatus.Running => "🔄",
                _ => "⏸"
            };

            content.Children.Add(new TextBlock
            {
                Text = $"{statusIcon} 步骤 {stepResult.StepId}",
                FontSize = 14,
                FontWeight = FontWeights.Bold
            });

            if (!string.IsNullOrEmpty(stepResult.Output))
            {
                content.Children.Add(new TextBlock
                {
                    Text = stepResult.Output,
                    FontSize = 12,
                    Foreground = new SolidColorBrush(Colors.Gray),
                    TextWrapping = TextWrapping.Wrap,
                    Margin = new Thickness(0, 5, 0, 0)
                });
            }

            card.Child = content;
            return card;
        }

        /// <summary>
        /// 更新执行监控显示
        /// </summary>
        private void UpdateExecutionMonitor(AutonomousPlanResult result)
        {
            ExecutionMonitorPanel.Children.Clear();

            var monitoringText = new TextBlock
            {
                Text = $@"📈 执行监控报告

🎯 性能指标：
- 执行时间：{result.MonitoringResult.PerformanceMetrics.ExecutionTime:hh\:mm\:ss}
- 任务完成：{result.MonitoringResult.PerformanceMetrics.TasksCompleted}
- 任务失败：{result.MonitoringResult.PerformanceMetrics.TasksFailed}
- 成功率：{result.MonitoringResult.PerformanceMetrics.SuccessRate:P}

🔧 优化建议：
{string.Join("\n", result.OptimizationSuggestions.Select(s => $"- {s.Description}"))}",
                FontSize = 12,
                TextWrapping = TextWrapping.Wrap,
                Margin = new Thickness(10)
            };

            ExecutionMonitorPanel.Children.Add(monitoringText);
        }

        /// <summary>
        /// 更新统计信息
        /// </summary>
        private void UpdateStatistics(AutonomousPlanResult result)
        {
            CreatedCharactersCount.Text = result.ExecutionResult.CharacterExecutionResult?.CreatedCharacters.Count.ToString() ?? "0";
            WorkflowStepsCount.Text = result.ExecutionResult.WorkflowExecutionResult?.StepResults.Count.ToString() ?? "0";
            AdjustmentsCount.Text = result.OptimizationSuggestions.Count.ToString();
            SuccessRate.Text = result.MonitoringResult.PerformanceMetrics.SuccessRate.ToString("P0");
        }

        /// <summary>
        /// 清空之前的结果
        /// </summary>
        private void ClearPreviousResults()
        {
            PlanOverviewPanel.Children.Clear();
            CharacterPlanPanel.Children.Clear();
            WorkflowPlanPanel.Children.Clear();
            ExecutionMonitorPanel.Children.Clear();

            CreatedCharactersCount.Text = "0";
            WorkflowStepsCount.Text = "0";
            AdjustmentsCount.Text = "0";
            SuccessRate.Text = "0%";

            ExecutionProgressBar.Value = 0;
            ProgressText.Text = "进度：0%";
        }

        /// <summary>
        /// 导出结果
        /// </summary>
        private void ExportResults()
        {
            var saveDialog = new Microsoft.Win32.SaveFileDialog
            {
                Filter = "JSON文件|*.json|文本文件|*.txt",
                DefaultExt = "json",
                FileName = $"自主规划结果_{DateTime.Now:yyyyMMdd_HHmmss}"
            };

            if (saveDialog.ShowDialog() == true)
            {
                try
                {
                    var json = System.Text.Json.JsonSerializer.Serialize(_currentResult, new System.Text.Json.JsonSerializerOptions
                    {
                        WriteIndented = true,
                        Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                    });

                    File.WriteAllText(saveDialog.FileName, json);
                    MessageBox.Show("结果导出成功！", "成功", MessageBoxButton.OK, MessageBoxImage.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"导出失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
        }

        /// <summary>
        /// 更新状态指示器
        /// </summary>
        private void UpdateStatusIndicator(string status, Color color)
        {
            StatusText.Text = status;
            StatusIndicator.Fill = new SolidColorBrush(color);
            StatusBarText.Text = $"智能自主规划系统 - {status}";
        }

        /// <summary>
        /// 添加日志
        /// </summary>
        private void AddLog(string message)
        {
            var timestamp = DateTime.Now.ToString("HH:mm:ss");
            var logEntry = $"[{timestamp}] {message}\n";

            LogTextBlock.Text += logEntry;
            LogScrollViewer.ScrollToEnd();
        }

        /// <summary>
        /// 获取当前项目ID
        /// </summary>
        private string? GetCurrentProjectId()
        {
            // 尝试从当前项目获取ID
            if (CurrentProject != null)
            {
                return CurrentProject.Id.ToString();
            }

            // 如果没有当前项目，返回null，将使用默认保存路径
            return null;
        }

        /// <summary>
        /// 获取首选的规划文件保存根路径（优先使用主GUI当前项目文件夹）
        /// </summary>
        private string? GetPreferredSaveRootPath()
        {
            try
            {
                // 优先从当前项目对象获取根路径
                if (CurrentProject != null && !string.IsNullOrWhiteSpace(CurrentProject.RootPath))
                {
                    return CurrentProject.RootPath;
                }

                // 其次尝试从主窗口的 DocumentEditorControl.CurrentProjectPath 获取
                if (Application.Current?.MainWindow is MainWindow main &&
                    !string.IsNullOrWhiteSpace(main?.DocumentEditorControl?.CurrentProjectPath))
                {
                    return main.DocumentEditorControl.CurrentProjectPath;
                }
            }
            catch
            {
                // 忽略，返回 null 走默认路径
            }
            return null;
        }


        /// <summary>
        /// 更新系统时间
        /// </summary>
        private void UpdateSystemTime()
        {
            SystemTimeText.Text = DateTime.Now.ToString("HH:mm:ss");
        }

        /// <summary>
        /// 状态定时器事件
        /// </summary>
        private void StatusTimer_Tick(object? sender, EventArgs e)
        {
            // 状态定时器现在只用于更新系统时间等非进度相关的状态
            // 进度更新由真实的进度回调处理
            UpdateSystemTime();
        }

        /// <summary>
        /// 时间计时器事件
        /// </summary>
        private void TimeElapsedTimer_Tick(object? sender, EventArgs e)
        {
            if (_isExecuting)
            {
                var elapsed = DateTime.Now - _executionStartTime;
                TimeElapsedText.Text = $"用时：{elapsed:hh\\:mm\\:ss}";
            }
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            if (_isExecuting)
            {
                var result = MessageBox.Show("规划正在执行中，确定要关闭吗？",
                    "确认", MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result == MessageBoxResult.No)
                {
                    e.Cancel = true;
                    return;
                }

                StopPlanning();
            }

            _statusTimer?.Stop();
            _timeElapsedTimer?.Stop();

            base.OnClosing(e);
        }
    }
}
